const express = require('express');
const fs = require('fs');
const path = require('path');
const router = express.Router();
// 在文件顶部添加颜色常量
const colors = {
    reset: '\x1b[0m',
    blue: '\x1b[34m',
    magenta: '\x1b[35m',
    gray: '\x1b[90m' // 新增灰色用于时间显示
};

// 新增北京时间格式化函数
function getBeijingTime() {
    return new Date().toLocaleString('zh-CN', {
        timeZone: 'Asia/Shanghai',
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        fractionalSecondDigits: 3
    }).replace(/(\d+)\/(\d+)\/(\d+),/, '$3-$1-$2 ').replace('上午', ' ').replace('下午', ' ');
}
function traverseRoutes(dir, parentPath = '') {
    const files = fs.readdirSync(dir);
    files.forEach(file => {
        const filePath = path.join(dir, file);
        const stat = fs.statSync(filePath);
        if (file === 'index.js') {
            return
        }
        if (stat.isDirectory()) {
            traverseRoutes(filePath, path.join(parentPath, file));
        } else if (path.extname(file) === '.js') {
            try {
                const routePath = path.join('/', parentPath, file.replace('.js', ''))
                    .replace(/\\/g, '/')
                    .replace(/\/\//g, '/');
                const routeModule = require(filePath);
                router.use(routePath, routeModule);
                console.log(`${colors.gray}[${getBeijingTime()}]${colors.reset} ${colors.magenta}✅ 自动注册路由: ${routePath}`)
            } catch (e) {
                console.error(`${colors.gray}[${getBeijingTime()}]${colors.reset} ${colors.magenta}🔥 加载失败: ${filePath}\n错误详情: ${e.stack}`)
            }
        }
    });
}
// 先换行 再打印彩色的文字 [路由模块]
console.log('')
console.log(`${colors.gray}[${getBeijingTime()}]${colors.reset} ${colors.magenta}[路由模块]`)
traverseRoutes(__dirname);
console.log('')
module.exports = router;